//
//  WBNetworkManager.swift
//  Weibo
//
//  Created by 伏文东 on 2018/1/24.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit
import AFNetworking


enum WBHTTPMethod {
    case GET
    case POST
}

/// 网络管理工具
class WBNetworkManager: AFHTTPSessionManager {
    /// 静态区 /常量 /闭包
    /// 在第一次访问时，执行闭包，并将结果保存在shared 常量中
    static let shared: WBNetworkManager = {
        let instance = WBNetworkManager()
        
        // 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()
    
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    /// 专门拼接token的网络请求方法
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) -> ())  {
        
        guard let token = userAccount.access_token else {
            print("没有toKen")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            completion(nil, false)
            return
        }
        
        // 处理touken 字典
        var parameters = parameters
        if parameters == nil {
            parameters = [String: Any]()
        }
        
        parameters!["access_token"] = token
        
        // 调用 request 发起真正的网络请求 方法
        request(URLString: URLString, parameters: parameters, completion: completion)
    }
    
    /// 使用一个函数封装 AFN 的 get / post 请求
    /// 封装AFN 的get
    ///
    /// - Parameters:
    ///   - method: get/ post
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 回调（字典， 是否成功）
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) -> ())  {
        // 成功回调
        let success = {(task: URLSessionDataTask, json: Any?) -> () in
            completion(json, true)
        }
        // 失败回调
        let failure = {(task: URLSessionDataTask?, error: Error) -> () in
            
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token 过期了 ")
                
                //FIXME: 发送通知
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                    object: "bad token")
            }
            
            print("网络请求错误\(error)")
            completion(nil, false)
        }
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
       
    }
}
